//
//  Manager.m
//  Sq
//
#import "Manager.h"

@implementation Manager
{
    
    sqlite3 *_db;
}

+ (instancetype)sharedManager {
    static Manager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        // 打开数据库
        [self openDbWithName:@"CarData.db"];
        // 创建表
        [self createTabel];
    }
    return self;
}
- (BOOL)execSql:(NSString *)sql {
    
    return sqlite3_exec(_db, sql.UTF8String, NULL, NULL, NULL) == SQLITE_OK;
}

- (void)createTabel {
    
    // 1. 读取创建表语句的内容
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Car.sql" ofType:nil];
    // 2. 取得二进制
    NSData *data = [NSData dataWithContentsOfFile:path];
    // 3. 转成字符串
    NSString *sql = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // 4. 执行sql语句
    if ([self execSql:sql]) {
        NSLog(@"创表成功");
        NSLog(@"");
    }else{
        NSLog(@"创表失败");
    }
}
- (void)openDbWithName:(NSString *)name {
    
    // 取得document目录
    NSString *folderPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).lastObject;
    // 将数据库的名字拼接到目录的后面
    NSString *filename = [folderPath stringByAppendingPathComponent:name];
    NSLog(@"数据库路径: %@", filename);

    
    if (sqlite3_open(filename.UTF8String, &_db) == SQLITE_OK) {
        NSLog(@"打开成功");
    }else{
        NSLog(@"打开失败");
    }
}
- (NSArray<NSDictionary *> *)execRecordSetWithSql:(NSString *)sql {
    // 1. 预编译sql
    sqlite3_stmt *stmt = NULL;
    
    if (sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
        NSLog(@"预编译成功");
    }else{
        NSLog(@"编译失败,sql语句有问题 %@", sql);
    }
    
    // 2. 取数据
    NSArray *result = [self recordSetWithStmt:stmt];
    
    // 3. 释放语句
    sqlite3_finalize(stmt);
    return result;
}
- (NSArray *)recordSetWithStmt:(sqlite3_stmt *)stmt {
    
    // 定义一个可变的数组
    NSMutableArray *result = [NSMutableArray array];
    
    // 如果能够取到一条数据,那么返回值就是SQLITE_ROW
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        // 如果代码执行到81行,代表已经取到一行,但是并不知道一行里面有哪些内容
        // 一行就代表一个字典
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        // 以下的代表都是以 sqlite3_column 开头
        // 取到这一句数据中有多少列
        int columnCount = sqlite3_column_count(stmt);
//        NSLog(@"%d",columnCount);
        for (int col = 0; col < columnCount; col++) {
            // 取列名,列名就是字典的key
            // c语言的列名
            const char *columnName = sqlite3_column_name(stmt, col);
            NSString *key = [NSString stringWithUTF8String:columnName];
            
            // 取值
            // 先取出类型
            int type = sqlite3_column_type(stmt, col);
            switch (type) {
                case SQLITE_INTEGER:{
                    // 取值
                    int value = sqlite3_column_int(stmt, col);
                    [dict setObject:@(value) forKey:key];
                    break;
                }
                case SQLITE3_TEXT: {
                    // 取到c语言的字符串
                    const char *cValue = (const char *)sqlite3_column_text(stmt, col);
                    // 转OC的字符串
                    NSString *value = [NSString stringWithUTF8String:cValue];
                    // 设置到字典里面去
                    [dict setObject:value forKey:key];
                    break;
                }
                case SQLITE_FLOAT:{
                    // 取值
                    double value = sqlite3_column_double(stmt, col);
                    [dict setObject:@(value) forKey:key];
                    break;
                }
                default:
                    break;
            }
            
        }
        // 将字典添加到数组中
        [result addObject:dict];
    }
    // 将返回值返回
    return result.copy;
}


@end
